﻿@using Abp.Extensions
@using Abp.Json
@using FutureGoodsItem = FutureApp.Shop.GoodsItem
@model FutureApp.Web.Models.Shop.GoodsViewModel

@section Scripts{
    <script>
        !function ($) {
            var $$$ = function () {
                this.$box = $('.box');
                this.$form = $('form');
                this.service = abp.services.app.goods;
                this.localize = abp.localization.localize;
                this.cache = {};
            };
            $$$.prototype = {
                init: function () {
                    this.formSubmit();
                    this.binding();
                    this.initMould();
                },
                initMould: function () {
                    var self = this;
                    var items = eval('@Html.Raw(this.Model.CurrentGoods.Mould.Attributes.ToJsonString(true)) ');
                    var data = eval('@Html.Raw(this.Model.CurrentGoods.GoodsList.ToJsonString(true)) ');
                    data = data.map(function (el) {
                        $.each(el.attributeDistribution, function () {
                            el[this.attributeId] = { id: this.attributeValueId, val: this.attrValue };
                        });
                        return el;
                    });
                    var $table = $('<table></table>');
                    $('#mouldCheck').append($table)
                        .on('change', 'input[type=checkbox]', function (e) {
                            var $sender = $(e.currentTarget),
                                field = $sender.data("field"),
                                uniqueid = $sender.data("unique-id"),
                                val = $sender.val(),
                                cache = self.cache[field];
                            var selection = { id: uniqueid, val: val };

                            if ($sender.prop("checked")) {
                                cache.push(selection);
                                var data = $.extend({}, self.cache);
                                data[field] = selection;
                                var rows = $.permutateArray(data);
                                $table.bootstrapTable('append', rows);
                            } else {
                                for (var len = cache.length, i = len - 1 ; i >= 0; i--) {
                                    if (_.isEqual(selection, cache[i])) {
                                        cache.splice(i, 1);
                                    }
                                }
                                $table.bootstrapTable('remove', { field: field, values: [selection] });
                            }
                        });

                    var columns = [
                        {
                            title: "",
                            searchable: false,
                            formatter: function (value, row, index) { return index + 1; },
                            align: "center",
                            valign: "middle"
                        }
                    ];
                    $.each(items, function (index, value, array) {
                        columns.push({
                            field: value.id,
                            title: value.name,
                            valign: "middle",
                            formatter: function (value) { return value.val; }
                        });
                        self.cache[value.id] = [];
                    });
                    columns = columns.concat([
                        {
                            field: '@("Quantity".ToCamelCase())',
                            title: self.localize("Stock"),
                            searchable: false,
                            input: true,
                            validate: function (val) {
                                return /^(0|\+?[1-9][0-9]*)$/.test(val);
                            }
                        },
                        {
                            field: '@("Price".ToCamelCase())',
                            title: self.localize("Price"),
                            searchable: false,
                            input: true,
                            validate: function (val) {
                                return /^\d+(\.\d+)?$/.test(val);
                            }
                        },
                        {
                            field: '@("SalePrice".ToCamelCase())',
                            title: self.localize("SalePrice"),
                            searchable: false,
                            input: true,
                            validate: function (val) {
                                return /^\d+(\.\d+)?$/.test(val);
                            }
                        },
                        {
                            field: '@("BottomPrice".ToCamelCase())',
                            title: self.localize("BottomPrice"),
                            searchable: false,
                            input: true,
                            validate: function (val) {
                                return /^\d+(\.\d+)?$/.test(val);
                            }
                        }
                    ]);
                    self.table = $table.bootstrapTable({
                        toggle: "table",
                        striped: true,
                        keyEvents: true,
                        sortable: false,
                        columns: columns
                    });
                    self.table.parents(".bootstrap-table").hide();
                    self.table.on('post-body.bs.table', function (_, data) {
                        if (data.length === 0) {
                            self.table.parents(".bootstrap-table").hide();
                        } else {
                            self.table.parents(".bootstrap-table").show();
                        }
                    });
                    $.each(data, function () {
                        $.each(this.attributeDistribution, function () {
                            var cache = self.cache[this.attributeId];
                            var selection = { id: this.attributeValueId, val: this.attrValue };
                            _.some(cache, function (o) { return _.isEqual(o, selection); }) || cache.push(selection);
                        });
                    });
                    $table.bootstrapTable('append', data);
                },
                formSubmit: function () {
                    this.$form.submit(function (e) {
                        e.preventDefault();
                    });
                },
                binding: function () {
                    var self = this;
                    self.$box.on("click", '.btn', function (e) {
                        e.preventDefault();

                        var $sender = $(e.currentTarget);
                        var action = $.trim($sender.data("action"));
                        switch (action) {
                            case "submit":
                                self.submit();
                                break;
                        }
                    });
                },
                submit: function () {
                    var self = this;
                    abp.ui.setBusy(self.$box);
                    var data = self.$form.serializeFormToObject();
                    data["skus"] =
                        _.map(self.table.bootstrapTable("getData"), function (el) {
                            var attrs = _.map(_.filter(_.values(el), function (val) { return val instanceof Object; }), function (val) { return val.id; });
                            return $.extend({ attrvalues: attrs }, el);
                        });
                    self.service.updateGoods(data)
                        .done(function () {
                            abp.message.success(self.localize("EditGoodsSucceed"))
                                .done(function () { location.href = "@Url.Action("list")"; });
                        })
                        .always(function () {
                            abp.ui.clearBusy(self.$box);
                        });
                }
            };

            $(function () { (new $$$()).init(); });
        }(jQuery);
    </script>
}
<ul class="content-nav">
    <li>
        <a href="@Url.Action("list")">@L("List")</a>
    </li>
    <li>
        <a href="@Url.Action("add")">@L("Add")</a>
    </li>
    <li class="active">
        <a href="javascript:;">@L("Edit")【@this.Model.CurrentGoods.Name】</a>
    </li>
</ul>
<div class="box box-success box-edge-all" data-dock="true">
    <form role="form">
        <div class="box-body">
            <input type="hidden" name="Id" value="@this.Model.CurrentGoods.Id" />
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsSerialNo")</label>
                        <input name="SerialNo"
                               type="text"
                               class="form-control"
                               maxlength="@FutureGoodsItem.MaxSerialNoLength"
                               value="@this.Model.CurrentGoods.SerialNo"
                               readonly>
                    </div>
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsName")</label>
                        <input name="Name"
                               type="text"
                               class="form-control"
                               maxlength="@FutureGoodsItem.MaxNameLength"
                               value="@this.Model.CurrentGoods.Name">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsBrand")</label>
                        <input name="BrandId" data-toggle="list-modal"
                               data-title="@L("GoodsBrand")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsBrand.getGoodsBrandList"
                               data-columns="[{ field: 'name', title: '@L("GoodsBrand")' }]"
                               value="@this.Model.CurrentGoods.Brand.Id" />
                    </div>
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsCategory")</label>
                        <input name="CategoryId" data-toggle="list-modal"
                               data-title="@L("GoodsCategory")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsCategory.getGoodsCategoryList"
                               data-columns="[{ field: 'name', title: '@L("GoodsCategory")' }]"
                               value="@this.Model.CurrentGoods.Category.Id" />
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsMould")</label>
                        <input name="MouldId" data-toggle="list-modal"
                               data-title="@L("GoodsMould")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsMould.getGoodsMouldList"
                               data-columns="[{ field: 'name', title: '@L("GoodsCategory")' }]"
                               data-render="mouldCheck"
                               value="@this.Model.CurrentGoods.Mould.Id"
                               disabled />
                    </div>
                </div>
            </div>
            <div class="row">
                <div id="mouldCheck" class="col-sm-10">
                    @foreach (var attr in this.Model.CurrentGoods.Mould.Attributes)
                    {
                        <div class="panel panel-info">
                            <div class="panel-heading">
                                <div class="row">
                                    <div class="col-md-4">@attr.Name</div>
                                    <div class="col-md-2 col-md-offset-6">
                                        <a class="pull-right" href="@Url.Action("Edit","GoodsAttributes",new { Id= attr.Id })">
                                            <i class="fa fa-plus"></i>
                                            <span class="bold">@L("Add")</span>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <div class="panel-body form-inline">
                                @foreach (var attrVal in attr.Values)
                                {
                                    var check = this.Model.CurrentGoods.GoodsList.Any(goods => goods.AttributeDistribution.Any(dsb => dsb.AttributeValueId == attrVal.Id));
                                    <div class="input-group" style="padding-right:10px;padding-bottom:10px;">
                                        <label class="input-group-addon input-group-check">
                                            @if (check)
                                            {
                                                <input type="radio" data-field="@attr.Id" data-unique-id="@attrVal.Id" value="@attrVal.Value" checked>
                                            }
                                            else
                                            {
                                                <input type="checkbox" data-field="@attr.Id" data-unique-id="@attrVal.Id" value="@attrVal.Value">
                                            }
                                            <i class="input-box"></i>
                                        </label>
                                        <input type="text" class="form-control" value="@attrVal.Value" readonly>
                                    </div>
                                }
                            </div>
                        </div>
                    }
                </div>
            </div>
        </div>
        <div class="box-footer">
            <a class="btn btn-primary" href="javascript:;" data-action="submit">
                <i class="fa fa-check"></i>
                @L("Submit")
            </a>
        </div>
    </form>
</div>